﻿#include "rulereader.h"


RuleReader::RuleReader(QString str, QObject *parent)
    : FileReader{str, parent}
{}

bool RuleReader::readFile()
{
    QFile file(getFilePath());

    // 读取json格式文件失败，返回
    if ( !file.open(QIODevice::ReadOnly)) {
        return false;
    }

    // 读取文件内容并关闭文件
    QByteArray jsonData = file.readAll();
    file.close();

    // 读取json格式
    QJsonDocument jd = QJsonDocument::fromJson(jsonData);
    // 判断json格式读取失败，返回
    if (!jd.isObject()) {
        qDebug()<<"format has error";
        return false;
    }

    // 读取json对象
    rootObject = jd.object();

    return true;
}



QString RuleReader::getRuleStringFromColumnObject(QJsonObject columnObject)
{
    QString ruleStr;

    if (!columnObject.isEmpty()) ruleStr = columnObject["Caculation"].toString();

    return ruleStr;
}


QStringList RuleReader::getRuleVariantListFromColumnObject(QJsonObject columnObject)
{
    QStringList resList;

    if (!columnObject.isEmpty()) {
        QJsonArray jsonArray = columnObject["Variants"].toArray();
        for (const QJsonValue& value : jsonArray) {
            if (value.isString()) {
                resList.append(value.toString());
            }
        }
    }

    return resList;
}

QJsonObject RuleReader::getColumnObjects(QString iCaseName)
{
    QJsonObject resObj;

    if (!rootObject.isEmpty()) resObj = rootObject[iCaseName].toObject()["Columns"].toObject();

    return resObj;
}



QStringList RuleReader::getCaseList()
{
    QStringList resList;

    if (!rootObject.isEmpty()) resList = rootObject.keys();

    return resList;
}

QHash<QString, QJsonObject> RuleReader::getLogFileters(QString iCaseName)
{
    QHash<QString, QJsonObject> resHash;

    if (!rootObject.isEmpty()) {
        QJsonObject subObj = rootObject[iCaseName].toObject()["LogFilters"].toObject();
        QStringList keys = subObj.keys();
        for(auto const &key : std::as_const(keys)) {
            resHash[key] = subObj[key].toObject();
        }
    }

    return resHash;
}
